import BaseSingleClass from "../base/BaseSingleClass";
import ToastDialog from "../components/popup/ToastDialog";
import PopupHelper from "../helper/PopupHelper";
import { Md5 } from "../utils/Md5";
type ParamConfig={
    token:string,
    url?:string,
    /**
     * 协议(http或https)
     */
    protocol?:string,
    host?:string
}
/**
 * 这是封装的接口api，可能每个项目都不一样，所以需要自己配置
 */
export default class APIHelper extends BaseSingleClass{
    //开发环境
    //private baseURL:string='https://app.fenzhidao.com/boot-app/api/v2/app/'
    //测试环境
    baseURL:string='http://app6.fenzhidao.com/inEnglish/api/v1/evaluation/'
    //域名
    baseURL1:string='http://app6.fenzhidao.com/'
    
    private timestamp: string = Date.parse(new Date().toString()) + ''
    private token: string = ""
    setToken(value:string){
        this.token=value
    }
    setURL(url:string){
        this.baseURL=url+'inEnglish/api/v1/evaluation/'
        //console.log('url:'+this.baseURL)
    }
    private getMd5Str():string {
        let str = this.token + "[" + this.token + this.timestamp + "]" + this.token;
        return Md5.hashStr(str) as string;
    }
    /**
     * 初始化配置
     * @param option ParamConfig
     */
    init(option:ParamConfig){
        if(option.protocol){
            this.init2(option.token,option.protocol,option.host)
        }else{
            this.init1(option.token,option.url)
        }
    }
    private init1(token:string='Bearer-556BEA81E287D0C3D832B1520ADC359350C11D2F6B32D7278301ED6863145E0D24AF22900DA462CD1FB8A55EEC177EE99328888D7BB6C0CC15B1FD71DA18D03D8951D74A9050D15D52C891C9EE978497',
    url='http://app6.fenzhidao.com/'):void{
        console.log('APIHelper init')
        this.token=token
        this.baseURL=url+'inEnglish/api/v1/evaluation/'
        this.baseURL1=url
        console.log('token:'+token)
        console.log('url:'+this.baseURL)
    }
    private init2(token:string,protocol:string,host:string){
        console.log('APIHelper init')
        this.token=token
        const url=protocol+'://'+host+'/'
        this.baseURL=url+'inEnglish/api/v1/evaluation/'
        console.log('token:'+token)
        console.log('url:'+this.baseURL)
    }
    private getHeaders():Headers{
        //this.token=VM.getValue("net.token")
        const headers=new Headers()
        headers.append('X-Authorization-Token',"Bearer-" + this.token)
        //headers.append('X-Authorization-Token',this.token)
        headers.append('timestamp',this.timestamp)
        headers.append('protocol',this.getMd5Str())
        return headers
    }
    /**
     * 参考下面两个示例，根据实际项目需求，封装自己的接口
     */
    logon(data:{account:string,code:string}):Promise<any>{
        const url=this.baseURL1+'inEnglish/api/v1/userAction/login'
        return new Promise<any>((resolve,reject)=>{
            this.request(url,{
                method: 'POST',
                //headers:this.headers,
                body: JSON.stringify(data),
                //redirect: 'follow'
            }).then(res=>{
                resolve(res.data)
            }).catch(reject)
        })
    }
    selectGradeGroup():Promise<any>{
        return new Promise((resolve,reject)=>{
            const url='selectGradeGroup'
            this.request(url,{
                method: 'GET',
                headers: this.getHeaders(),
                //params: {userTrainingId:id},
                //redirect: 'follow'
            }).then(res=>{
                resolve(res.data)
            }).catch(reject)
        })
    }
    /**
     * request请求，所有接口都基于这个封装
     * @param url 地址
     * @param config 配置(method,headers,body)
     * @returns 
     */
    private request(url:string,config:any):Promise<any>{
        return new Promise((resolve,reject)=>{
            const link=(url.indexOf('http')==-1)?this.baseURL+url:url
            fetch(link,config).then(response=>{
                if(response.ok){
                    response.text().then(res=>{
                        const json=JSON.parse(res)
                        /**
                         * 200表示成功，其他表示失败，例如-50表示token失效，根据项目实际需求作修改
                         */
                        if(json.code==200){
                            //console.log(json.data)
                            resolve(json)
                        }else if(json.code==500){
                            reject(json)
                        }else if(json.code==-50){
                            //token失效，弹窗提示
                            const pop=PopupHelper.getInstance()
                            const node=pop.openDialog('ToastDialog',{onSuccess:()=>{
                                //token失效,跳转登录界面
                                //@ts-ignore
                                wx.miniProgram.navigateTo({url: '/pages/login/wechat'})
                                reject(null)
                            },onClose:()=>{
                                reject(null)
                            }})
                            /*node.getComponent(ToastDialog).dataSource={
                                title:'账号异常提醒',
                                content:'您的账号可能存在在其他设备登录或登录记录已失效的情况,请重新登录或退出使用!',
                                type:'warn',
                                btOk:'重新登录',
                                showClose:false
                            }*/
                            alert('账号异常提醒')
                            
                        }else{
                            //console.error(json.message)
                            //director.emit(GameEvent.SHOW_TOAST,json.message)
                            reject(json)
                        }
                    }).catch(reject)
                }else{
                    reject(response)
                }
            }).catch(reject)
        })
        //return fetch(this.baseURL+url,config)
    }
}